package com.heng.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heng.dao.entity.Coupon;
import com.heng.dao.entity.UserCoupon;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

// 用户优惠券Mapper
public interface UserCouponMapper extends BaseMapper<UserCoupon> {
    // 查询用户领取的优惠券数量（用于限制每人限领）
    @Select("SELECT COUNT(*) FROM t_user_coupon " +
            "WHERE user_id = #{userId} AND coupon_id = #{couponId} " +
            "AND use_status IN (0, 2)") // 未使用+已过期视为已领取
    Integer selectCountByUserAndCoupon(@Param("userId") Long userId, @Param("couponId") Long couponId);

    // 查询用户可用优惠券（未使用、在有效期内、满足满减条件）
    @Select("SELECT uc.* FROM t_user_coupon uc " +
            "LEFT JOIN t_coupon c ON uc.coupon_id = c.id " +
            "WHERE uc.user_id = #{userId} " +
            "AND uc.use_status = 0 " +
            "AND c.status = 1 " +
            "AND c.start_time <= NOW() " +
            "AND c.end_time >= NOW() " +
            "AND (c.type = 1 OR c.full_price <= #{productPrice}) " + // 无门槛或满足满减
            "ORDER BY c.amount DESC") // 按优惠金额降序
    @Results({
        @Result(column = "coupon_id", property = "coupon", 
                one = @One(select = "com.heng.dao.mapper.CouponMapper.selectById"))
    })
    List<UserCoupon> selectAvailableCoupons(@Param("userId") Long userId,
                                            @Param("productPrice") BigDecimal productPrice);

    // 更新用户优惠券状态（使用/过期）
    @Update("UPDATE t_user_coupon " +
            "SET use_status = #{useStatus}, use_time = #{useTime}, order_id = #{orderId} " +
            "WHERE id = #{id} AND user_id = #{userId}")
    boolean updateUserCouponStatus(@Param("id") Long id, 
                                  @Param("userId") Long userId, 
                                  @Param("useStatus") Integer useStatus, 
                                  @Param("useTime") LocalDateTime useTime,
                                  @Param("orderId") Long orderId);
}